package st.business.tepth.business.taskallocation.detail;

import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.jakewharton.rxbinding2.widget.RxTextView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import st.business.tepth.R;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.FactoryGroupBean;
import st.business.tepth.business.bean.PersonBean;
import st.business.tepth.business.bean.post.TaskAllocationDetail;
import st.business.tepth.config.ItemFields;
import st.business.tepth.config.Url;
import st.business.tepth.manager.UserManager;
import st.business.tepth.view.ClearEditText;
import st.shadow.library.core.net.callback.IError;
import st.shadow.library.core.net.callback.ISuccess;
import st.shadow.library.core.net.data.ObjConverter;
import st.shadow.library.core.net.rx.RxRestClient;
import st.shadow.library.core.util.utilcode.util.DeviceUtils;
import st.shadow.library.core.util.utilcode.util.ToastUtils;
import st.shadow.library.ui.recycler.MultipleItemEntity;

/**
 * @author zhangyu
 * @date 2019/7/3
 */
public class DialogChooseOtherPerson extends Dialog {
    private List<MultipleItemEntity> mCheckedList = new ArrayList<>();
    private Disposable mDisposable;

    public DialogChooseOtherPerson(@NonNull Context context,
                                   final OnItemChooseListener<List<MultipleItemEntity>> listener) {
        super(context);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = LayoutInflater.from(context).
                inflate(R.layout.dialog_choose_other_person, null);
        view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        view.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCheckedList == null || mCheckedList.isEmpty()) {
                    ToastUtils.showShort("请先选择作业人");
                } else {
                    if (listener != null) {
                        listener.onChoose(mCheckedList);
                    }
                    dismiss();
                }
            }
        });
        final RecyclerView recyclerViewSearch = view.findViewById(R.id.recycler_view);
        recyclerViewSearch.setLayoutManager(new GridLayoutManager(context, 3));
        final SearchAdapter searchAdapter = new SearchAdapter(null);
        ClearEditText etSearch = view.findViewById(R.id.et_search);
        Observer observable = RxTextView.textChanges(etSearch)
                .subscribeOn(AndroidSchedulers.mainThread())
                .debounce(600, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .filter(new Predicate<CharSequence>() {
                    @Override
                    public boolean test(CharSequence charSequence) throws Exception {
                        return charSequence.length() > 0;
                    }
                })
                .map(new Function<CharSequence, Integer>() {
                    @Override
                    public Integer apply(CharSequence charSequence) throws Exception {
                        List<MultipleItemEntity> dataList = searchAdapter.getData();
                        String key = charSequence.toString();
                        for (int i = 0, size = dataList.size(); i < size; i++) {
                            MultipleItemEntity entity = dataList.get(i);
                            if (entity.getItemType() == SearchAdapter.TYPE_ITEM) {
                                TaskAllocationDetail.Person personBean = entity.getField(ItemFields.ITEM_OBJ);
                                String name = personBean.getUser_name();
                                String no = personBean.getJob_no();
                                if (key.equals(name) || key.equals(no)) {
                                    return i;
                                }
                            }
                        }
                        return -1;
                    }
                })
                .subscribeWith(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer o) {
                        if (o != -1) {
                            MultipleItemEntity entity = searchAdapter.getItem(o);
                            if (entity != null) {
                                boolean checked = entity.getField("checked");
                                if (!checked) {
                                    entity.setField("checked", true);
                                    mCheckedList.add(entity);
                                    searchAdapter.notifyItemChanged(o);
                                }
                                if (o > 10 && o < searchAdapter.getData().size() - 10) {
                                    recyclerViewSearch.scrollToPosition(o + 6);
                                } else {
                                    recyclerViewSearch.scrollToPosition(o);
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


        searchAdapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() {
            @Override
            public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
                MultipleItemEntity entity = searchAdapter.getItem(position);
                return entity == null ? 3 : (entity.getItemType() == SearchAdapter.TYPE_HEAD ?
                        3 : 1);
            }
        });
        recyclerViewSearch.setAdapter(searchAdapter);
        searchAdapter.setEmptyView(R.layout.view_loading,
                (ViewGroup) recyclerViewSearch.getParent());
        mDisposable = RxRestClient.builder().url(Url.GetOtherPerson)
                .params("workbenchNo", DeviceUtils.getAndroidID())
                .params("token", UserManager.getInstance().getToken())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        searchAdapter.setEmptyView(R.layout.view_search_empty,
                                (ViewGroup) recyclerViewSearch.getParent());
                        searchAdapter.setNewData(convertData(response));
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        searchAdapter.setEmptyView(R.layout.view_search_empty,
                                (ViewGroup) recyclerViewSearch.getParent());
                        searchAdapter.setNewData(null);
                    }
                }).build().get();
        setContentView(view);
    }

    @Override
    public void dismiss() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        super.dismiss();
    }

    private List<MultipleItemEntity> convertData(String response) {
        List<FactoryGroupBean> list = new ObjConverter<List<FactoryGroupBean>>().convert(response
                , new TypeReference<List<FactoryGroupBean>>() {
                });
        List<MultipleItemEntity> dataList = new ArrayList<>();
        if (list != null) {
            for (FactoryGroupBean factoryGroupBean : list) {
                dataList.add(MultipleItemEntity.builder()
                        .setItemType(SearchAdapter.TYPE_HEAD)
                        .setField("group", factoryGroupBean.getGroupName())
                        .build());
                List<PersonBean> personBeans = factoryGroupBean.getMember();
                if (personBeans != null) {
                    for (PersonBean personBean : personBeans) {
                        dataList.add(MultipleItemEntity.builder()
                                .setItemType(SearchAdapter.TYPE_ITEM)
                                .setField("checked", false)
                                .setField("cancelable", false)
                                .setField("classId", 0)
                                .setField("personId", personBean.getId())
                                .setField("isFinish", false)
                                .setField(ItemFields.ITEM_OBJ,
                                        new TaskAllocationDetail.Person(personBean.getUser_name(),
                                                personBean.getJob_no(), false,personBean.getId()))
                                .build());
                    }
                }
            }
        }
        return dataList;
    }

    private class SearchAdapter extends
            BaseMultiItemQuickAdapter<MultipleItemEntity, BaseViewHolder> {
        static final int TYPE_HEAD = 0;
        static final int TYPE_ITEM = 1;

        SearchAdapter(List<MultipleItemEntity> data) {
            super(data);
            addItemType(TYPE_HEAD, R.layout.item_choose_other_person_type_head);
            addItemType(TYPE_ITEM, R.layout.item_choose_other_person_type_item);
        }

        @Override
        protected void convert(final BaseViewHolder helper, final MultipleItemEntity item) {
            switch (item.getItemType()) {
                case TYPE_HEAD:
                    helper.setText(R.id.tv_name, (CharSequence) item.getField("group"));
                    break;
                case TYPE_ITEM:
                    helper.setChecked(R.id.check_person, (Boolean) item.getField("checked"));
                    helper.getView(R.id.layout_checkbox).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            boolean isChecked = item.getField("checked");
                            helper.setChecked(R.id.check_person, !isChecked);
                            item.setField("checked", !isChecked);
                            if (!isChecked) {
                                mCheckedList.add(item);
                            } else {
                                mCheckedList.remove(item);
                            }
                        }
                    });
                    TaskAllocationDetail.Person personBean = item.getField(ItemFields.ITEM_OBJ);
                    helper.setText(R.id.check_person,
                            String.format("%s(%s)", personBean.getUser_name(),
                                    personBean.getJob_no()));
                    break;
            }
        }
    }
}
